package salomon.manager 
{
	import salomon.event.TextureManagerEvent;
	import salomon.loader.TextureLoader;
	import salomon.utils.Alert;
	import starling.events.Event;
	import starling.events.EventDispatcher;
	import starling.textures.TextureAtlas;
	/**
	  * <p>Descreva a funcionalidade deste singleton.</p>
	  * <p>Autor Tiago Salomon</p>
	  * 
	  * @author Tiago Salomon
	 */	
	public class TextureManager extends EventDispatcher
	{
		
		private var _textures		: Vector.<TextureLoader>;
		private var _indexLoaded	: uint = 0;
		private var _totalTextures	: uint = 0;
		
		public function TextureManager () 
		{
			_textures = new Vector.<TextureLoader>();			
		}
			
		/********** PRIVATE ****************************************/
				
		/********** HANDLER ****************************************/		

		private function onTextureAdded(e:Event):void 
		{
			var tx:TextureLoader = e.currentTarget as TextureLoader;			
			
			var progress:Number = Math.round(_indexLoaded / _totalTextures) * 100;
						
			this.dispatchEvent(new TextureManagerEvent(TextureManagerEvent.PROGRESS, false, false, { progress:progress } ));
			
			if (++_indexLoaded >= _totalTextures)
				this.dispatchEvent(new TextureManagerEvent(TextureManagerEvent.COMPLETE, false, false, null ));
				
		}
		
		/********** PUBLIC *****************************************/		

		public function initialize():void 
		{
			for each (var text:TextureLoader in this._textures) 
			{
				text.loadTexture();
			}
		}
		
		public function addItem(name:String, xmlPath:String, spriteSheetPath:String):void 
		{			
			var txCont:TextureLoader = new TextureLoader(name, xmlPath, spriteSheetPath)
				txCont.addEventListener(Event.ADDED, onTextureAdded);
			
			_textures.push(txCont);
			_totalTextures++;
		}

		public function getItem(name:String):TextureAtlas
		{

			var textureAtlas:TextureAtlas;
			
			for each (var text:TextureLoader in this._textures) 
			{
				if (text.name == name)
					textureAtlas = text.atlas;				
			}
			
			if (textureAtlas == null)
				throw new Error("TextureManager->getTexture |63| TEXTURA NÃO ENCONTRADA.");
			
			return textureAtlas;
			
		}
		
		/********** GET / SET ***************************************/		
		
	}
}
